<script setup lang="ts">
import Topic from '@/components/Topic.vue'
import { ref, computed } from 'vue'
import Reply from '@/components/Reply.vue'
import { MoreFilled, Promotion } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  adminAddCommentService, adminAskReasonCommentService,
  adminDeleteCommentService,
  adminGetCommentListService,
  adminGetTopicDetailService
} from '@/api/admin'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const topicId = ref(route.params.id)
console.log(topicId.value)

const topic = ref({
  id: 1,
  title: 'TCP和UDP有什么区别',
  publisher: '胡清钟',
  identify: '教师',
  content: '我觉得意大利面就该拌32号混凝土，因为螺丝钉的长度会直接影响挖掘机的扭矩',
  image: '',
  createTime: '2024-12-04',
  watch: '10',
  reply: '2',
  like: '5'
})

interface Comment {
  id: number
  publisher: string
  content: string
  createTime: string
  identify: string
  avatar: String
}

const commentList = ref<Comment[]>([
  // {
  //   id: 1,
  //   publisher: '朱原味',
  //   content: '啊对对对，你说的都对，但是原神是由米哈游自主研发的……',
  //   createTime: '2024-12-05',
  //   identify: 'student'
  // }
])

enum identifyType {
  'teacher' = 'success',
  'student' = 'primary'
}

enum identifyCN {
  'teacher' = '老师',
  'student' = '学生'
}

const reply = ref()

// 我的评论
const myComment = ref('')

// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = 5
// 总记录数
const totalRecords = ref(0)
// 判断是否已经加载到底
const noMoreData = computed(() => {
  console.log(commentList.value.length, totalRecords.value)
  return commentList.value.length >= totalRecords.value
})

const loading = ref(false)
const disabled = computed(() => loading.value)

const getTopicDetail = async () => {
  const res = await adminGetTopicDetailService(topicId.value)
  topic.value = res.data.data
}

getTopicDetail()

const getCommentList = async () => {
  if (loading.value) return // 防止重复请求
  loading.value = true

  const res = await adminGetCommentListService(currentPage.value, topicId.value)
  console.log(res.data.data.records)
  const data = res.data.data

  // 更新总记录数
  totalRecords.value = data.total // 假设总记录数字段名为 totalRecords

  // 如果返回的数据存在评论，直接赋值到 commentList
  if (data.records.length > 0) {
    if (currentPage.value === 1) {
      // 如果是第一页，重新赋值，不进行拼接
      commentList.value = data.records
    } else {
      // 如果是分页加载，拼接新数据
      commentList.value = [...commentList.value, ...data.records]
    }
  }

  loading.value = false
}

getCommentList()

// 加载更多评论
const load = async () => {
  if (loading.value || noMoreData.value) return // 如果正在加载或者没有更多数据，则不执行

  currentPage.value += 1
  await getCommentList()
}

// 滚动事件监听
const onScroll = () => {
  if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 100) {
    load()
  }
}

// 监听滚动事件
window.addEventListener('scroll', onScroll)

// 发表我的评论
const submitMyComment = async () => {
  if (myComment.value.trim() === '') {
    ElMessage.warning('评论内容不能为空')
    return
  }
  await adminAddCommentService(myComment.value, topicId.value)
  currentPage.value = 1
  await getCommentList() // 更新评论列表
  await getTopicDetail() // 更新话题详情
  // 清空评论框
  myComment.value = ''
}

// const deleteComment = async (id: any) => {
//   console.log(id)
//   await ElMessageBox.confirm('确认删除吗？', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   })
//   await adminDeleteCommentService(id)
//   ElMessage.success('删除成功')
//   currentPage.value = 1
//   await getCommentList()
// }

const useStore = useUserStore()

// 删除时的弹窗
const isShowDeleteDialog = ref(false)
const deleteReason = ref({
  id:'',
  reason:'',
  anotherReason:''
})
const willDeleteTopic = ref()

// 暂存要删除的话题id
const willDelete = (topic: Object) => {
  if (topic.identify === 'student'){
    isShowDeleteDialog.value = true
  }
  willDeleteTopic.value = topic
  deleteReason.value.id = willDeleteTopic.value.id
  if (topic.identify === 'teacher'){
    deleteTopic()
  }
}

// 删除话题
const deleteTopic = async () => {
  if (!willDeleteTopic.value) return
  await ElMessageBox.confirm(
    `此操作将永久删除该话题, 是否继续?`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )

  if (willDeleteTopic.value.identify === 'student'){
    await adminAskReasonCommentService(deleteReason.value)
  }
  await adminDeleteCommentService(willDeleteTopic.value.id)
  console.log(deleteReason.value)
  ElMessage.success('删除成功')
  isShowDeleteDialog.value = false
  deleteReason.value.reason = ''
  deleteReason.value.anotherReason = ''
  deleteReason.value.reason = ''
}
</script>

<template>
  <div id="main-topicContent">
    <Topic class="topic">
      <template #title>{{ topic.title }}</template>
      <template #publisher>{{ topic.publisher }}</template>
      <template #identify>
        <el-tag :type="identifyType[topic.identify]" style="margin-left: 5px"
          >{{ identifyCN[topic.identify] }}
        </el-tag>
      </template>
      <template #content>{{ topic.content }}</template>
      <template #image>
        <img
          v-if="topic.image"
          :src="topic.image"
          style="height: 180px; width: auto; border-radius: 5px"
          alt=""
        />
      </template>
      <template #createTime>{{ topic.createTime }}</template>
      <template #watch>{{ topic.watch }}</template>
      <template #reply>{{ topic.reply }}</template>
      <template #like>{{ topic.like }}</template>
    </Topic>
    <h3 style="margin-left: 20px">评论区</h3>
    <div class="reply-area">
      <el-scrollbar class="infinite-list-wrapper" style="overflow: auto">
        <div v-infinite-scroll="load" class="list" :infinite-scroll-disabled="disabled">
          <div v-for="comment in commentList" :key="comment.id">
            <Reply ref="reply" class="reply">
              <template #avatar>
                <img :src="comment.avatar" id="avatar" alt="" />
              </template>
              <template #delete>
                <el-dropdown style="margin-right: 20px">
                  <el-icon class="el-icon--right">
                    <MoreFilled />
                  </el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="willDelete(comment)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
              <template #publisher>{{ comment.publisher }}</template>
              <template #content>{{ comment.content }}</template>
              <template #createTime>{{ comment.createTime }}</template>
              <template #identify>
                <el-tag :type="identifyType[comment.identify]" style="margin-left: 5px"
                  >{{ identifyCN[comment.identify] }}
                </el-tag>
              </template>
            </Reply>
            <el-divider />
          </div>
          <!-- 没有更多数据时显示提示 -->
          <div v-if="noMoreData" class="no-more-data">
            <el-alert title="没有更多数据了" type="info" center />
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="remark-area">
      <img :src="useStore.getAvatar()" id="avatar" alt="" />
      <el-input
        style="flex: 1; height: 50px; margin-left: 10px"
        maxlength="50"
        placeholder="请发表你的见解吧"
        show-word-limit
        v-model="myComment"
        @keyup.enter="submitMyComment"
      ></el-input>
      <el-button
        :icon="Promotion"
        circle
        style="height: 50px; width: 50px; right: 0; position: relative; margin-left: 10px"
        type="primary"
        @click="submitMyComment"
      ></el-button>
    </div>

    <!-- 删除确认弹窗 -->
    <el-dialog append-to-body v-model="isShowDeleteDialog" width="400">
      <div>
        <h1 style="text-align: center">删除理由</h1>
        <el-form style="margin-top: 10px">
          <el-form-item>
            <el-select v-model="deleteReason.reason" placeholder="请选择删除理由">
              <el-option label="语言包含违规词汇" value="语言包含违规词汇" />
              <el-option label="话题引战" value="话题引战" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-if="deleteReason.reason === '其他'"
              v-model="deleteReason.anotherReason"
              placeholder="请输入理由"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="btn-area">
          <el-button type="primary" @click="deleteTopic">确认</el-button>
          <el-button type="warning" @click="isShowDeleteDialog = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
#main-topicContent {
  position: relative;
  width: 100%;
}

.reply-area {
  margin: 20px;
  overflow: hidden;
  background-color: #fff;
  border-radius: 10px;
}

.remark-area {
  padding: 10px;
  backdrop-filter: blur(10px);
  webkit-backdrop-filter: blur(10px);
  margin: 20px;
  display: flex;
  align-items: center;
  width: 95%;
  height: 60px;
  position: relative;
  bottom: 0;
  background-color: #fff;
  border-radius: 10px;
}

#avatar {
  overflow: hidden;
  height: 40px;
  width: 40px;
  clip-path: circle(50% at 50% 50%);
}

.infinite-list-wrapper {
  height: 55vh;
}

.no-more-data {
  text-align: center;
  margin-top: 20px;
}

</style>
